import React from 'react';
import {Menu, Icon} from 'antd';
import {Link} from 'react-router-dom';
import * as images from '../style/imgs';


const SubMenu = Menu.SubMenu;
const Item = Menu.Item;
const iconSizeWidth = 19,iconSizeHeight = 21;
const renderMenuItem = (item, permission) => {
    if (!permission.includes(item.permission)) {
        return;
    }
    return (    // item.route 菜单单独跳转的路由
        <Item key={item.key}>
            <Link to={item.route || item.key}>
                {images[item.icon] && <img src={images[item.icon]} width={iconSizeWidth} height={iconSizeHeight} style={{marginRight: 10}}/>}
                <span className="nav-text">{item.title}</span>
            </Link>
        </Item>
    );
}

const renderSubMenu = (item, permission,level) => {
    if (!permission.includes(item.permission)) {
        return;
    }
    return (
        <SubMenu
            key={item.key}
            className={`subMenu${level}`}
            title={
                <span>
                {images[item.icon] && <img src={images[item.icon]} width={iconSizeWidth} height={iconSizeHeight} style={{marginRight: 10}}/>}
                    <span className="nav-text">{item.title}</span>
            </span>
            }
        >
            {item.subs.map(item => item.subs ? renderSubMenu(item, permission,level+1) : renderMenuItem(item, permission))}
        </SubMenu>
    );
}

const supplyMenu = (menus, permission, parentMenu = []) => {
    menus.map(item => {
        if (permission.includes(item.permission) && !parentMenu.length) {
            return;
        }
        if (item.subs) {
            supplyMenu(item.subs, permission, [...parentMenu, item]);
        } else {
            if (permission.includes(item.permission)) {
                parentMenu.map(parentItem => {
                    if (!permission.includes(parentItem.permission)) {
                        permission.push(parentItem.permission);
                    }
                });
            } else if (item.permission.split(':')[0] == permission[permission.length - 1].split(':')[0]) {
                parentMenu.map(parentItem => {
                    if (!permission.includes(parentItem.permission)) {
                        permission.push(parentItem.permission);
                    }
                });
                permission.push(item.permission);
            }
        }

    });
    return permission;
}

export default ({menus, permission, ...props}) => (
    <Menu {...props}>
        {menus && menus.map(item => {
                if (permission && permission.length) {
                    permission = supplyMenu(menus, permission);
                    return item.subs ? renderSubMenu(item, permission,0) : renderMenuItem(item, permission);
                }
            }
        )}
    </Menu>
);